package com.qf.controller.market;

import com.alibaba.druid.util.StringUtils;
import com.qf.pojo.DtsCategory;
import com.qf.service.DtsCategoryService;
import com.qf.util.ResponseUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @author bss
 * @version V1.0
 * @Project maven
 * @Package com.qf.controller.market
 * @Description:
 * @Date 2022/10/18 20:40
 */
@RestController
@RequestMapping("/admin/category")
public class AdminCategoryController {
    @Autowired
    DtsCategoryService categoryService;


    @GetMapping("/list")
    public Object list(@RequestParam(value = "page",required = false,defaultValue = "1") Integer page ,
                       @RequestParam(value = "limit",required = false,defaultValue = "20") Integer limit,
                       @RequestParam(value = "sort",required = false,defaultValue = "add_time") String sort,
                       @RequestParam(value = "order",required = false,defaultValue = "desc") String order,
                       Integer id, String name){
        Map<String,Object> data = categoryService.selectByPage(page,limit,sort,order,id,name);
        return ResponseUtil.ok(data);
    }

    @GetMapping("/l1")
    public Object l1(){
        List<Map<String,Object>> data = categoryService.findCategoryL1List();
        return ResponseUtil.ok(data);

    }

    @PostMapping("/update")
    public Object update(@RequestBody DtsCategory category){
        Object result = checkDtsCategory(category);
        if (result!=null){
            return result;
        }
        category.setUpdateTime(new Date());
        categoryService.update(category);
        return ResponseUtil.ok();
    }
    private Object checkDtsCategory(DtsCategory category) {
        if (StringUtils.isEmpty(category.getName()) || StringUtils.isEmpty(category.getDesc())|| category.getDesc()==null){
            return ResponseUtil.fail(-1,"类目名称、关键字和类目简介不能为空");
        }
        if (category.getLevel()==null){
            return ResponseUtil.fail(-1,"级别不能为空");
        }
        return null;
    }


    @PostMapping("/create")
    public Object create(@RequestBody DtsCategory category){
        Object result = checkDtsCategory(category);
        if (result != null){
            return result;
        }
        category.setAddTime(new Date());
        category.setUpdateTime(new Date());
        category.setDeleted(false);


        try {
            categoryService.insert(category);
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseUtil.fail(-1,e.getMessage());
        }

        return ResponseUtil.ok(category);
    }


    @PostMapping("/delete")
    public Object delete(@RequestBody DtsCategory category){
        categoryService.delete(category);
        return ResponseUtil.ok();
    }
}
